package com.ojoin.ojoin.eb_spider.service.catchdata;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.ojoin.ojoin.eb_spider.domain.BankCardCheck;
import com.ojoin.ojoin.eb_spider.service.SupplyPaymentService;
import com.ojoin.ojoin.eb_spider.service.impl.SLDataCatchBaseServiceImpl;
import com.ojoin.trade.common.exception.BusinessException;
import com.ojoin.trade.common.utils.LogUtils;
import com.ojoin.trade.common.utils.NumberUtils;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlSupplyPayment;

/**
 * 
 * 
 * 
 */

@Service
public class SupplierGOMEDataCatchServiceImpl extends
		SLDataCatchBaseServiceImpl {

	private Logger log = LoggerFactory
			.getLogger(SupplierGOMEDataCatchServiceImpl.class);

	// 保存公司基本信息 key name 名字 bankNum 结款账号

	Map<String, String> map = new HashMap<String, String>();

	@Autowired
	private SupplyPaymentService paymentService;

	@Override
	public boolean LoginByUserInfo(String baseUrl, String username,
			String password) {
		// 开始登陆
		this.getWebDriver().get(baseUrl);

		this.getWebDriver().sendKeys("id", "username", username);
		this.getWebDriver().sendKeys("id", "password", password);

		this.getWebDriver()
				.click("css",
						"#TabbedPanels1 div div.TabbedPanelsContent.TabbedPanelsContentVisible table  tbody tr:nth-child(5)  td:nth-child(2)  a");

		return this.getWebDriver().isLogin(
				"http://b2bi.gome.com.cn/mainLogon.hlt");

	}

	// 验证码处理
	public void verifycode() {

	}

	@Override
	public String catchSupplierName() throws BusinessException {
		initCompanyInfomation();
		String name = "";
		if (null != map) {
			name = map.get("name");
		}
		return name;
	}

	@Override
	public BankCardCheck catchSupplierAccount() throws BusinessException {
	    initCompanyInfomation();
	    BankCardCheck bcc = new BankCardCheck();
		
		
		String bankNum = "";
		if (null != map) {
			bankNum = map.get("bankNum");
		}

		bcc.setBankNum(bankNum);
		return bcc;
	}

	public void initCompanyInfomation() {

		Map<String, TbSlSupplyPayment> waitpay =  this.getAssistCatchData().getStartMess()
				.getWaitpay();

		Set<String> set = waitpay.keySet();
		
		Iterator<String> it = set.iterator();

		if (it.hasNext()) {
			String en = it.next();
			String contractUrl = "http://b2bi.gome.com.cn/gmol/buyGrnDel/detail.hlt?editType=edit&grnno="
					+ en;
			this.getWebDriver().get(contractUrl);

			String name = this.getWebDriver().getText("css", "#base_table > tbody > tr:nth-child(10) > td:nth-child(2)");
			
			String bankNum = this.getWebDriver().getText("css", "#base_table > tbody > tr:nth-child(11) > td:nth-child(2)");

			map.put("name", name);
			map.put("bankNum", bankNum);

		}
		// http://b2bi.gome.com.cn/gmol/sellVatInvQry/detail.hlt?invid=2041525

	}

	@Override
	public boolean getUnpayAccountData() throws BusinessException {

		Map<String, TbSlSupplyPayment> waitpay =  this.getAssistCatchData().getStartMess()
				.getWaitpay();

		List<TbSlSupplyPayment> payments = new ArrayList<TbSlSupplyPayment>();

		try {
			String fiveDayPurchase = "http://b2bi.gome.com.cn/mainLogon.hlt#";

			this.getWebDriver().get(fiveDayPurchase);

			this.getWebDriver().switchToframe("initFrame");

			this.getWebDriver()
					.findElement("css", "#shortcutBtn > li:nth-child(1)")
					.click();

			this.getWebDriver().switchToDefaultContent();

			WebElement frame = this
					.getWebDriver()
					.findElement(
							"css",
							"#main-center1  div.tabs-panels.tabs-panels-noborder  div:nth-child(2)  div  iframe");

			this.getWebDriver().switchToframe(frame);

			this.getWebDriver()
					.click("css",
							"#hide_table > tbody > tr.form_bottom > td > a:nth-child(3)");

			if(!this.getWebDriver().IsExist("css","#row > tbody")){
				return true ;
			}
			WebElement web = this.getWebDriver().findElement("css",
					"#row > tbody");

			List<WebElement> trs = web.findElements(By.tagName("tr"));

			if (null != trs && !trs.isEmpty()) {
				Iterator<WebElement> it = trs.iterator();
				while (it.hasNext()) {
					WebElement tr = it.next();
					// LogUtils.info(log,tr.getText());
					TbSlSupplyPayment payment = new TbSlSupplyPayment();
					payment.setPlatformAccountId( this.getAssistCatchData().getStartMess()
							.getPlatformUser().getId());

					try {
						List<WebElement> tds = tr
								.findElements(By.tagName("td"));
						// LogUtils.info(log,tds.get(6).getText());

						//
						WebElement invoiceid = tds.get(5);
						WebElement webendtime = tds.get(6);
						WebElement Invoicetatol = tds.get(10);

						String endtime = webendtime.getText();

						String settlementId = invoiceid.getText();

						String amountD = Invoicetatol.getText();
						amountD = amountD.replace(",", "");
						long amount = NumberUtils.getLongAmount(amountD);

						payment.setSettlementId(settlementId);
						payment.setCreateDate(endtime);
						payment.setAmount(amount);
						payment.setSettlementState(TbSlSupplyPayment.WAITPAY);

						payments.add(payment);

					} catch (Exception e) {
						if (trs.size() != 1) {
							LogUtils.error(log, e);
							// throw e;
						}
					}
				}
			}
		} catch (Exception e) {
			LogUtils.error(log, e);
			throw e;
		}

		paymentService.removeSettlementCommon(payments, waitpay);
		List<TbSlSupplyPayment> li = paymentService.changeToPay(waitpay);

		 this.getAssistCatchData().getCata().setPayupdate(li);

		 this.getAssistCatchData().getCata().setSettlement(payments);

		return true;

	}

	@Override
	public boolean getInstoreOrderData() throws BusinessException {

		return true;
	}

	@Override
	public boolean getOutstoreOrderData() throws BusinessException {
		// 送货记录
		// 对账单
		return true;
	}

	@Override
	public boolean getPayAccountData() throws BusinessException {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public BankCardCheck isSupplyAccountCorrect() throws BusinessException {
		BankCardCheck bcc = new BankCardCheck();
		bcc.setCorrect(true);
		
		return bcc;
	}
}
